<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="住户名称" prop="householdName">
        <el-input v-model="queryParams.householdName" placeholder="请输入住户名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="房屋地址" prop="houseAddress">
        <el-input v-model="queryParams.houseAddress" placeholder="请输入房屋地址" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="单元号" prop="unitNo">
        <el-input v-model="queryParams.unitNo" placeholder="请输入单元号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="户号" prop="householdNo">
        <el-input v-model="queryParams.householdNo" placeholder="请输入户号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['house:household:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['house:household:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="householdList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="住户ID" align="center" prop="householdId" /> -->
      <el-table-column label="住户名称" align="center" prop="householdName" />
      <el-table-column label="房屋地址" align="center" prop="houseAddress" :show-overflow-tooltip="true"/>
      <el-table-column label="单元号" align="center" prop="unitNo" />
      <el-table-column label="户号" align="center" prop="householdNo" />
      <el-table-column label="使用权人" align="center" prop="userRightPerson" />
      <el-table-column label="使用权证号" align="center" prop="userRightCertificate" />
      <el-table-column label="是否自行装修" align="center" prop="isDecorated">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no_num" :value="scope.row.isDecorated"/>
        </template>
      </el-table-column>
      <el-table-column label="违法拆改结构" align="center" prop="isStructureChanged">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no_num" :value="scope.row.isStructureChanged"/>
        </template>
      </el-table-column>
      <el-table-column label="排查时间" align="center" prop="inspectionTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inspectionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['house:household:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['house:household:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="住户名称" prop="householdName">
              <el-input v-model="form.householdName" placeholder="请输入住户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属房屋" prop="houseId">
              <el-input
                v-model="houseInfo"
                placeholder="请选择所属房屋"
                readonly
                @click.native="openHouseSelect"
              >
                <el-button slot="append" icon="el-icon-search" @click.stop="openHouseSelect"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="房屋地址" prop="houseAddress">
              <el-input v-model="form.houseAddress" placeholder="请输入房屋地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单元号" prop="unitNo">
              <el-input v-model="form.unitNo" placeholder="请输入单元号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="户号" prop="householdNo">
              <el-input v-model="form.householdNo" placeholder="请输入户号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用权人" prop="userRightPerson">
              <el-input v-model="form.userRightPerson" placeholder="请输入使用权人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="使用权证号" prop="userRightCertificate">
              <el-input v-model="form.userRightCertificate" placeholder="请输入使用权证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否自行装修" prop="isDecorated">
              <el-radio-group v-model="form.isDecorated">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no_num"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="违法拆改结构" prop="isStructureChanged">
              <el-radio-group v-model="form.isStructureChanged">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no_num"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有无违章搭建" prop="hasIllegalBuilding">
              <el-radio-group v-model="form.hasIllegalBuilding">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no_num"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="改变房屋用途" prop="isPurposeChanged">
              <el-radio-group v-model="form.isPurposeChanged">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no_num"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="屋面渗漏" prop="hasRoofLeak">
              <el-radio-group v-model="form.hasRoofLeak">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no_num"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="门窗脱落" prop="hasDoorWindowLoose">
              <el-radio-group v-model="form.hasDoorWindowLoose">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no_num"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用电防火" prop="hasElectricFireProtection">
              <el-radio-group v-model="form.hasElectricFireProtection">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no_num"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用气防火" prop="hasGasFireProtection">
              <el-radio-group v-model="form.hasGasFireProtection">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no_num"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="堆放易燃物" prop="hasFlammableStorage">
              <el-radio-group v-model="form.hasFlammableStorage">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no_num"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="排查时间" prop="inspectionTime">
              <el-date-picker
                v-model="form.inspectionTime"
                type="datetime"
                placeholder="选择排查时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他问题" prop="otherIssues">
              <el-input v-model="form.otherIssues" type="textarea" placeholder="请输入其他问题" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="具体情况描述" prop="situationDescription">
              <el-input v-model="form.situationDescription" type="textarea" placeholder="请输入具体情况描述" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="工作措施" prop="workMeasures">
              <el-input v-model="form.workMeasures" type="textarea" placeholder="请输入工作措施" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 房屋选择弹窗 -->
    <el-dialog :title="'选择房屋'" :visible.sync="houseSelectVisible" width="1000px" append-to-body>
      <!-- 搜索条件 -->
      <el-form :model="houseQueryParams" ref="houseQueryForm" :inline="true" label-width="68px">
        <el-form-item label="房屋名称" prop="houseName">
          <el-input
            v-model="houseQueryParams.houseName"
            placeholder="请输入房屋名称"
            clearable
            size="small"
            @keyup.enter.native="handleHouseQuery"
          />
        </el-form-item>
        <el-form-item label="房屋编号" prop="houseCode">
          <el-input
            v-model="houseQueryParams.houseCode"
            placeholder="请输入房屋编号"
            clearable
            size="small"
            @keyup.enter.native="handleHouseQuery"
          />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select 
            v-model="houseQueryParams.province" 
            placeholder="请选择省份" 
            clearable 
            size="small"
            @change="handleProvinceChange"
            @clear="handleProvinceClear"
          >
            <el-option
              v-for="item in provinceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select 
            v-model="houseQueryParams.city" 
            placeholder="请选择城市" 
            clearable 
            size="small"
            @change="handleCityChange"
            @clear="handleCityClear"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="district">
          <el-select 
            v-model="houseQueryParams.district" 
            placeholder="请选择区域" 
            clearable 
            size="small"
            @clear="handleDistrictClear"
          >
            <el-option
              v-for="item in districtOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleHouseQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetHouseQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 房屋列表 -->
      <el-table
        v-loading="houseLoading"
        :data="houseList"
        @row-click="handleSelectHouse"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="房屋名称" prop="houseName" />
        <el-table-column label="房屋编号" prop="houseCode" />
        <el-table-column label="地址" prop="address" :show-overflow-tooltip="true"/>
        <el-table-column label="建筑面积" prop="buildingArea" align="center" />
        <el-table-column label="风险等级" align="center" prop="riskLevel">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.house_risk_level" :value="scope.row.riskLevel"/>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="houseTotal>0"
        :total="houseTotal"
        :page.sync="houseQueryParams.pageNum"
        :limit.sync="houseQueryParams.pageSize"
        @pagination="getHouseList"
      />
    </el-dialog>
  </div>
</template> 

<script>
import { listHousehold, getHousehold, delHousehold, addHousehold, updateHousehold } from "@/api/house/household";
import { listHouse } from "@/api/house/house";
import { listProvinceOptions } from "@/api/house/province";
import { listCityOptions } from "@/api/house/city";
import { listDistrictOptions } from "@/api/house/district";

export default {
  name: "Household",
  dicts: ['sys_yes_no_num'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 户表格数据
      householdList: [],
      // 房屋列表数据
      houseOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        householdName: null,
        houseAddress: null,
        unitNo: null,
        householdNo: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        householdName: [
          { required: true, message: "住户名称不能为空", trigger: "blur" }
        ],
        houseId: [
          { required: true, message: "所属房屋不能为空", trigger: "change" }
        ],
        houseAddress: [
          { required: true, message: "房屋地址不能为空", trigger: "blur" }
        ],
        unitNo: [
          { required: true, message: "单元号不能为空", trigger: "blur" }
        ],
        householdNo: [
          { required: true, message: "户号不能为空", trigger: "blur" }
        ]
      },
      // 房屋选择弹窗相关数据
      houseSelectVisible: false,
      houseInfo: '',
      houseLoading: false,
      houseList: [],
      houseTotal: 0,
      houseQueryParams: {
        pageNum: 1,
        pageSize: 10,
        houseName: null,
        houseCode: null,
        province: null,
        city: null,
        district: null
      },
      // 省市区数据
      provinceOptions: [],
      cityOptions: [],
      districtOptions: []
    };
  },
  created() {
    this.getList();
    this.loadProvinceOptions();
  },
  methods: {
    /** 查询户列表 */
    getList() {
      this.loading = true;
      listHousehold(this.queryParams).then(response => {
        this.householdList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取房屋列表 */
    getHouseList() {
      this.houseLoading = true;
      listHouse(this.houseQueryParams).then(response => {
        this.houseList = response.rows;
        this.houseTotal = response.total;
        this.houseLoading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        householdId: null,
        householdName: null,
        houseId: null,
        houseAddress: null,
        unitNo: null,
        householdNo: null,
        userRightPerson: null,
        userRightCertificate: null,
        isDecorated: "0",
        isStructureChanged: "0",
        hasIllegalBuilding: "0",
        isPurposeChanged: "0",
        hasRoofLeak: "0",
        hasDoorWindowLoose: "0",
        hasElectricFireProtection: "0",
        hasGasFireProtection: "0",
        hasFlammableStorage: "0",
        otherIssues: null,
        situationDescription: null,
        workMeasures: null,
        inspectionTime: null
      };
      this.resetForm("form");
      this.houseInfo = '';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.householdId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加住户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const householdId = row.householdId || this.ids
      getHousehold(householdId).then(response => {
        this.form = response.data;
        // 获取房屋信息并设置显示
        if (this.form.houseId) {
          listHouse({
            houseId: this.form.houseId
          }).then(res => {
            if (res.rows && res.rows.length > 0) {
              const house = res.rows[0];
              this.houseInfo = `${house.houseName}（${house.houseCode}）`;
            }
          });
        }
        this.open = true;
        this.title = "修改住户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 转换日期格式
          if (this.form.inspectionTime) {
            this.form.inspectionTime = this.parseTime(this.form.inspectionTime, '{y}-{m}-{d} {h}:{i}:{s}');
          }
          
          if (this.form.householdId != null) {
            updateHousehold(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHousehold(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const householdIds = row.householdId || this.ids;
      this.$modal.confirm('是否确认删除户编号为"' + householdIds + '"的数据项？').then(function() {
        return delHousehold(householdIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('house/household/export', {
        ...this.queryParams
      }, `household_${new Date().getTime()}.xlsx`)
    },
    /** 打开房屋选择弹窗 */
    openHouseSelect() {
      this.houseSelectVisible = true;
      this.getHouseList();
    },
    
    /** 查询房屋列表 */
    getHouseList() {
      this.houseLoading = true;
      listHouse(this.houseQueryParams).then(response => {
        this.houseList = response.rows;
        this.houseTotal = response.total;
        this.houseLoading = false;
      });
    },
    
    /** 选择房屋 */
    handleSelectHouse(row) {
      this.form.houseId = row.houseId;
      this.form.houseAddress = row.address;
      this.houseInfo = `${row.houseName}（${row.houseCode}）`;
      this.houseSelectVisible = false;
    },
    
    /** 搜索房屋按钮操作 */
    handleHouseQuery() {
      this.houseQueryParams.pageNum = 1;
      this.getHouseList();
    },
    
    /** 重置房屋查询操作 */
    resetHouseQuery() {
      this.resetForm("houseQueryForm");
      this.houseQueryParams.province = null;
      this.houseQueryParams.city = null;
      this.houseQueryParams.district = null;
      this.cityOptions = [];
      this.districtOptions = [];
      this.handleHouseQuery();
    },

    /** 加载省份数据 */
    loadProvinceOptions() {
      listProvinceOptions().then(response => {
        this.provinceOptions = response.rows.map(item => ({
          value: item.provinceCode,
          label: item.provinceName
        }));
      });
    },

    /** 加载城市数据 */
    loadCityOptions(provinceCode) {
      listCityOptions({ provinceCode: provinceCode }).then(response => {
        this.cityOptions = response.rows.map(item => ({
          value: item.cityCode,
          label: item.cityName
        }));
      });
    },

    /** 加载区域数据 */
    loadDistrictOptions(cityCode) {
      listDistrictOptions({ cityCode: cityCode }).then(response => {
        this.districtOptions = response.rows.map(item => ({
          value: item.districtCode,
          label: item.districtName
        }));
      });
    },

    /** 省份选择改变事件 */
    handleProvinceChange(value) {
      if (value) {
        this.loadCityOptions(value);
        this.houseQueryParams.city = null;
        this.houseQueryParams.district = null;
        this.cityOptions = [];
        this.districtOptions = [];
      }
    },

    /** 城市选择改变事件 */
    handleCityChange(value) {
      if (value) {
        this.loadDistrictOptions(value);
        this.houseQueryParams.district = null;
        this.districtOptions = [];
      }
    },

    /** 省份清除事件 */
    handleProvinceClear() {
      this.houseQueryParams.city = null;
      this.houseQueryParams.district = null;
      this.cityOptions = [];
      this.districtOptions = [];
    },

    /** 城市清除事件 */
    handleCityClear() {
      this.houseQueryParams.district = null;
      this.districtOptions = [];
    },

    /** 区域清除事件 */
    handleDistrictClear() {
      this.houseQueryParams.district = null;
    }
  }
};
</script> 